import os

def process_catia_caa_files(input_dir, output_dir):
    """
    Scans an input directory for .h and .cpp files, combines their contents,
    and writes them to output files with a maximum size of 256KB.
    Tries UTF-8 encoding first, and falls back to ISO-8859-1 if it fails.

    Args:
        input_dir (str): The path to the input directory.
        output_dir (str): The path to the output directory.
    """
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    combined_content = ""
    output_file_counter = 1
    max_file_size = 256 * 1024  # 256KB

    for root, _, files in os.walk(input_dir):
        for filename in files:
            if filename.endswith((".h", ".cpp")):
                file_path = os.path.join(root, filename)
                content = None
                try:
                    with open(file_path, 'r', encoding='utf-8') as f:
                        content = f.read()
                except UnicodeDecodeError:
                    try:
                        with open(file_path, 'r', encoding='ISO-8859-1') as f:
                            content = f.read()
                        print(f"Successfully read {filename} with ISO-8859-1 encoding.")
                    except Exception as e:
                        print(f"Error reading file: {file_path} with both UTF-8 and ISO-8859-1 - {e}")
                        continue
                except Exception as e:
                    print(f"Error opening file: {file_path} - {e}")
                    continue

                if content is not None:
                    entry = f"```{filename}\n{content}\n```\n"
                    if len(combined_content.encode('utf-8')) + len(entry.encode('utf-8')) <= max_file_size:
                        combined_content += entry
                    else:
                        # Write the current combined content to a file
                        output_filename = os.path.join(output_dir, f"catia_caa_{output_file_counter}.md")
                        with open(output_filename, 'w', encoding='utf-8') as outfile:
                            outfile.write(combined_content)
                        print(f"Wrote file: {output_filename}")

                        # Start a new combined content with the current file
                        combined_content = entry
                        output_file_counter += 1

    # Write any remaining combined content to a file
    if combined_content:
        output_filename = os.path.join(output_dir, f"catia_caa_{output_file_counter}.md")
        with open(output_filename, 'w', encoding='utf-8') as outfile:
            outfile.write(combined_content)
        print(f"Wrote file: {output_filename}")

if __name__ == "__main__":
    input_directory = "D:\\software\\CATIA\\CAADoc\\"
    output_directory = "D:\\BaiduNetdiskDownload\\ima_catia_caa\\"
    process_catia_caa_files(input_directory, output_directory)
    print("Processing complete.")